package com.gp.ajax.app2;

import com.gp.ajax.app2.com.gp.ajax.app2.beans.ShoppingCart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "addToCart")
public class addToCart extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数:bookName、piece
        String bookName = request.getParameter("id");
        double piece = Double.parseDouble(request.getParameter("price").trim());
        //2.获取购物车对象
        HttpSession session = request.getSession();
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
        if (shoppingCart == null) {
            shoppingCart = new ShoppingCart();
            session.setAttribute("shoppingCart", shoppingCart);
        }
        //3.把点击的对象加入到购物车中
        shoppingCart.addToCart(bookName, piece);
        //4.准备响应的JSON对象
//        ObjectMapper objectMapper = new ObjectMapper();
//        String result = objectMapper.writeValueAsString(shoppingCart);
        StringBuilder result = new StringBuilder();
        result.append("{")
                .append("\"bookName\":\"" + bookName + "\"")
                .append(",")
                .append("\"totalBookNumber\":\"" + shoppingCart.getTotalBookNumer() + "\"")
                .append(",")
                .append("\"totalMoney\":\"" + shoppingCart.getTotalMoney() + "\"")
                .append("}");
        //5.响应JSON对象
        session.setAttribute("result", result);
        response.setContentType("text/javascript;charset=utf-8");
        response.getWriter().print(result);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
